# -*- coding: utf-8 -*-
# @Date     : 2021/4/9 11:46
# @Author   : xiaochuang.wu
# @File     : lock.py
"""
通过设置一个key成功与否模拟锁功能
cli 为异步Redis client
"""


class LockbyRedis(object):
    @staticmethod
    async def get_lock(cli, key, expire):
        if expire and not isinstance(expire, int):
            return False
        ans = await cli.setnx(key, 1)
        if not ans:
            return False
        if expire:
            ret = await cli.expire(key, expire)
            if not ret:
                await cli.delete(key)
                return False
        return True

    @staticmethod
    async def check_lock(cli, key):
        """ttl=-1 不过期, ttl=-2 key不存在"""
        ttl = await cli.ttl(key)
        return ttl

    @staticmethod
    async def remove_lock(cli, key):
        if await cli.exists(key):
            return await cli.delete(key)
        return True
